/*****************************************************************************
 *
 *              Timer.c -- Timer Counter Program
 *
 *****************************************************************************
 * FileName:        Timer.c
 *
 * Model:       	ATmega644
 *
 * Author:          Sheng Chen and Eric DeYoung
 *
 * Date:            Nov 22, 2008
 *
 * Description:     Timer Counter Program 
 *
 *****************************************************************************/


#include <avr/io.h>
#include <avr/interrupt.h>
#include "utility.h"

volatile uint16_t Seconds = 0;
volatile uint16_t TimeOut = 0;
volatile uint8_t  One_Second;
volatile uint8_t  ReadVoltage_delay = 0;

void timer_init(void)
{
	TCCR0B = _BV(CS00) | _BV(CS02);  //1024 : 1   8-Bit Timer

	TCCR1B = _BV(CS10) | _BV(CS12);  //1024 : 1  16-Bit Timer

	TCCR2B = _BV(CS20); //1:1 8-Bit Timer

	TIMSK1 |= _BV(TOIE1); // Enable overflow interrupt on Timer 1
}

void delay_ns(uint8_t cycle) //1 cycle = 100 ns
{
	TCNT2=0;

	OCR2B=cycle;

	TIFR2=_BV(OCF2B);

	while( (TIFR2 & _BV(OCF2B)) == 0);
}


void delay(uint8_t cycle) //1 cycle = 102.4 us Using Timer 1
{
	TCNT0=0;

	OCR0A=cycle;

	TIFR0=_BV(OCF0A);

	while( (TIFR0 & _BV(OCF0A)) == 0);
}

void Wait_2_sec(void) //Wait 2 Seconds
{
	volatile uint8_t k;
	
	for(k=0; k<76;k++)
		delay(255);
}

void Wait_1_sec(void) //Wait 1 Second
{
	volatile uint8_t k;
	
	for(k=0; k<38; k++)
		delay(255);
}

ISR(TIMER1_OVF_vect) //Second Counter
{
	TimeOut++;
	Seconds++;
	ReadVoltage_delay++;

	One_Second = 1;

/*	if(ReadVoltage_delay > 3) //Take Battery Voltage Reading every 20 seconds
	{
		read_voltage();
		read_temperature();
		ReadVoltage_delay = 0;
	} */

	if(TimeOut > 75) //Turn off LCD Backligh after 75 seconds if not pushbutton is pressed
			PORTD &= ~_BV(4); 

	TCNT1 = 55769; //It takes 1 second to count from 55769 to 65535
}
